//
//  AppDelegate.m
//  myProject
//
//  Created by 王涛 on 15/5/28.
//  Copyright (c) 2015年 王涛. All rights reserved.
//

#import "AppDelegate.h"
#import <Fabric/Fabric.h>
#import <Crashlytics/Crashlytics.h>
#import "SmudgyWindow.h"
#import "SMGuideVC.h"
#import "SMLoginVC.h"
#import "SMRegisterVC.h"
#import "SMHomeVC.h"
#import "SMFindVC.h"
#import "SMPictureVC.h"
#import "SMMineVC.h"
#import "FFNavigationController.h"
#import "MainTabBarVC.h"

@interface AppDelegate ()

@end

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
//    /*
//     * 获取定位服务许可
//     */
//    [self initCoreLocationService];
//    /**
//     * 开始定位服务
//     */
//    [self initLocationService];
    /*
     * 初始化网络接口
     */
    [self initNetwork];
//    /*
//     * 初始化支付
//     */
//    [self initPaymentService];
//    /**
//     * Fabric
//     */
//    [Fabric with:@[CrashlyticsKit]];
    /**
     *  窗口初始化 FIXME SmudgyWindow -> UIWindow 去掉点击效果
     */
    self.window = [[SmudgyWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    self.window.backgroundColor = [UIColor whiteColor];
    [self.window makeKeyAndVisible];
    //根据各种状态控制流程，是否是第一次登录，是否自动登录等等.分别进入不同的流程：欢迎页，登录页，主页面，如果需要。还有城市选择页
    // Guide.
    //================测试代码，进入主页================
//    [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"first launch"];
//    [[Cache sharedCache] setUserID:222];
    //================测试代码========================
    
    if (![[NSUserDefaults standardUserDefaults] boolForKey:@"first launch"]) {//第一次登录进入欢迎页
        [self presentTutorialViewController];
        [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"first launch"];
    } else {
        //两种判断网络的方法，可选 isExistNetWork/checkNetworkConnection
        if (![[LocationService sharedLocationService] isExistNetWork]) { // 如果没有网络
            [self presentTutorialViewController];
            [Utils showAlertView:@"注意" :@"您当前的网络不可用" :@"我知道了"];
        } else if ([Cache sharedCache].userID) { //自动登录
            [self presentMenuViewController:NO];
        } else { //去登陆页
            [self presentSigninViewController:NO];
        }
    }
    
    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0) {//8.0以后使用这种方法来注册推送通知
        [[UIApplication sharedApplication]registerUserNotificationSettings:[UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeAlert|UIUserNotificationTypeBadge|UIUserNotificationTypeSound  categories:nil]];
    } else {
        [application registerForRemoteNotificationTypes: UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeSound];
    }
    return YES;
}

- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    
    [self doCleanup];
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
#pragma mark - Initialization

- (void)initCoreLocationService { // iOS 8 needed
    CLLocationManager *locationManager = [Utils locMgr];
    
    // fix ios8 location issue
    if ([CLLocationManager authorizationStatus] == kCLAuthorizationStatusNotDetermined) {
#ifdef __IPHONE_8_0
        if ([locationManager respondsToSelector:@selector(requestAlwaysAuthorization)])
        {
            [locationManager performSelector:@selector(requestAlwaysAuthorization)];//用这个方法，plist中需要NSLocationAlwaysUsageDescription
        }
        
        if ([locationManager respondsToSelector:@selector(requestWhenInUseAuthorization)])
        {
            [locationManager performSelector:@selector(requestWhenInUseAuthorization)];//用这个方法，plist里要加字段NSLocationWhenInUseUsageDescription
        }
#endif
    }
}
- (void)initLocationService {
    [[LocationService sharedLocationService] start];
}
- (void)doCleanup {
    //取消通知，停止各种服务
    [[LocationService sharedLocationService] stop];
}
- (void)initNetwork {
    //给网络请求设置基本URL
    [[NetWorkRequest sharedNetWorkRequest] setBasicURL:kApiBasePublicUrl];
}
- (void)initPaymentService {
    //FiXME:未完成
}
#pragma mark - Navigation control

- (void)replaceRootControllerBy:(UIViewController *)vc {
    
    [self presentMenuViewController:NO];
}

#pragma mark - Main view branching

#pragma mark 欢迎页
- (void)presentTutorialViewController {
    //进入欢迎页
    SMGuideVC *guideVC = [[SMGuideVC alloc]init];
    FFNavigationController *myNav = [[FFNavigationController alloc] initWithRootViewController:guideVC];
    [AppAppearance appearance];
    [self.window setRootViewController:myNav];
}

#pragma mark 登录页：自动登录
- (void)presentSigninViewController {
    [self presentSigninViewController:NO];
};

#pragma mark 登录页
- (void)presentSigninViewController:(BOOL)autoLogin {
    SMLoginVC *loginVC = [[SMLoginVC alloc]init];
    loginVC.fromPageTagStr = @"backHome";

    FFNavigationController *myNav = [[FFNavigationController alloc] initWithRootViewController:loginVC];
    [AppAppearance appearance];
    [self.window setRootViewController:myNav];
}

#pragma mark 注册页
- (void)presentRegistViewController {
    SMRegisterVC *registVC = [[SMRegisterVC alloc]init];
    [self replaceRootControllerBy:registVC];
}

// 应用主页
- (void)presentMenuViewController:(BOOL)isStart {
    MainTabBarVC *tabbarVC = [[MainTabBarVC alloc] init];
    [self.window setRootViewController:tabbarVC];
    [self.window makeKeyAndVisible];
}
// 弹出城市选择页
- (void)presentCitySelectViewController {
   
}

@end
